<template>
    <div>
        <!-- <h3>用户管理</h3> -->
        <!-- 查询 -->
        <div>
            <el-form :inline="true" :v-model="user" class="demo-form-inline">
                <el-form-item label="登陆名称:">
                    <el-input v-model="user.userName" placeholder="登陆名称" size="small"></el-input>
                </el-form-item>
                <el-form-item label="用户名字:">
                    <el-input v-model="user.realName" placeholder="用户姓名" size="small"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="queryUnitList" size="small">查询</el-button>
                    <el-button icon="el-icon-search" @click="redirectUnitList" size="small">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
         <!-- 按钮 -->
        <div>
            <el-button type="primary" icon="el-icon-plus" @click="showEditDialog" size="small">添加</el-button>
            <!-- <el-button type="primary" icon="el-icon-bottom" size="small">导入</el-button>
            <el-button type="primary" icon="el-icon-top" size="small">导出</el-button> -->
            <el-button type="primary" v-show="deleteMore" icon="el-icon-delete-solid" @click="deleteMoreBotton" size="small">批量删除</el-button>
        </div>
        <!-- 表格 -->
        <div>
            <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="userId" label="#" width="112"/>
                <el-table-column prop="userName" label="登陆名称" width="112"/>
                <el-table-column prop="realName" label="用户姓名" width="112"/>
                <el-table-column prop="userAddress" label="地址" width="112"/>
                <el-table-column prop="userTime" label="入职时间" width="112" show-overflow-tooltip/>
                <el-table-column prop="userPhone" label="电话" width="112"/>
                <el-table-column prop="role.roleName" label="角色" width="112"/>
                <el-table-column
                    label="操作"
                    >
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">修改</el-button>
                        <!-- 添加/删除人脸 -->
                        <el-button @click="scanFace(scope.row)" type="success" size="mini">{{scope.row.faceToken==''?"人脸添加":"人脸修改"}}</el-button>
                        <!-- 删除 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.userId)">删除</el-button>
                        <!-- 重置密码 -->
                        <el-button type="info" icon="el-icon-edit-outline" size="mini" @click="resetUserPwd(scope.row)">重置密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <Page
            @on-change="queryUnitList"
            :total="tocal"
            show-total
            :page-size="pageSize"
            style="float:right"/>
            <!-- 修改、添加 -->
            <div style="width: 100%">
                <el-dialog :title="uORiText" width="80%" :visible.sync="updateFormVisible" :before-close="handleClose">
                    <el-form :model="updateform" :rules="userRules" :inline="true" class="demo-form-inline">
                        <el-col>
                            <el-form-item prop="userName" label="登陆名称">
                                <el-input v-model="updateform.userName" placeholder="登录名称" autocomplete="off" size="medium"/>
                            </el-form-item>
                            <el-form-item prop="realName" label="用户姓名">
                                <el-input v-model="updateform.realName" placeholder="用户姓名" autocomplete="off" size="medium"/>
                            </el-form-item> <!-- 密码默认为123456 盐自生成-->
                            <el-form-item label="角色">
                                <!-- <el-input v-model="updateform.role.roleName" autocomplete="off" size="medium"/> -->
                                <el-select v-model="updateform.roleId" placeholder="请选择商品单位" size="medium">
                                    <el-option v-for="item in roleSelect" :key="item.roleId" :label="item.roleName" :value="item.roleId"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        
                        <br>

                        <el-col>
                            <el-form-item label="地址">
                                <el-input v-model="updateform.userAddress" placeholder="地址" autocomplete="off" size="medium"/>
                            </el-form-item>
                            <el-form-item prop="userBank" label="银行卡号">
                                <el-input v-model="updateform.userBank" placeholder="银行卡号" autocomplete="off" size="medium"/>
                            </el-form-item>
                            <el-form-item label="性别">
                                <el-select v-model="updateform.userSex" placeholder="性别" size="medium">
                                    <el-option label="女" value="女"/>
                                    <el-option label="男" value="男"/>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <br>
                        
                        <el-col>
                            <el-form-item label="入职时间">
                                <el-date-picker
                                v-model="updateform.userTime"
                                type="datetime"
                                placeholder="选择日期"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss"/>
                            </el-form-item>
                            <el-form-item prop="userPhone" label="电话">
                                <el-input v-model="updateform.userPhone" placeholder="电话" autocomplete="off" size="medium"/>
                            </el-form-item>
                            <el-form-item prop="userEmail" label="邮箱">
                                <el-input v-model="updateform.userEmail" placeholder="邮箱" autocomplete="off" size="medium"/>
                            </el-form-item>
                        </el-col>
                        
                        <br>
                        
                        <el-col>
                            <el-form-item prop="userIdcard" label="身份证号">
                                <el-input v-model="updateform.userIdcard" placeholder="身份证号" autocomplete="off" size="medium"/>
                            </el-form-item>
                        </el-col>
                        
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="updateFormVisible=false">取 消</el-button>
                        <el-button type="primary" @click="insertUpdateForm">确 定</el-button>
                    </div>
                </el-dialog>
            </div>
            <!-- 人脸注册框 -->
            <Modal
                v-model="dialogVisible"
                title="人脸检测"
                @on-ok="ok"
                @on-cancel="cancel"
                :z-index=3000>
                <div class="media">
                    <video id="video" width="450" height="300" src="" autoplay></video>
                    <canvas id="canvas" width="450" height="300"></canvas>
                </div>
            </Modal>
        </div>
    </div>
</template>
<script>
import axios from "axios"
export default {
    data() {
        // 手机号码验证
        var checkPhone = (rule, value, callback) => {
            const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
            if (!value) {
                return callback(new Error('手机号不能为空'));
            } else if (reg.test(value)) {
                    return callback(new Error('请输入正确的手机号'));
            } else {
                callback()
            }
        };
        // 身份证号码验证
        var checkIdNum = (rule, value, callback) => {
            const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
            if (!value) {
                return callback(new Error('证件号码不能为空'))
            } else if (!reg.test(value)) {
                return callback(new Error('证件号码不正确'))
            } else {
                callback()
            }
        };
        // 邮箱验证
        var checkEmail = (rule, value, callback) => {
            const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            if (!value) {
                return callback(new Error('邮箱不能为空'))
            }else if(!reg.test(value)){
                return callback(new Error('请输入正确的邮箱格式'))
            }else{
                callback()
            }
        };
        // 银行卡号验证
        var checkBank = (rule, value, callback) => {
            const reg = /^([1-9]{1})(\d{14}|\d{18})$/
            if (!value) {
                return callback(new Error('银行卡号不能为空'))
            }else if(!reg.test(value)){
                return callback(new Error('请输入正确的银行卡号格式'))
            }else{
                callback()
            }
        }
        return {
            // 查询条件
            user:{
                userName:'',
                realName:'',
            },
            user1:{
                userName:'',
                realName:'',
            },
            // 表格
            tableData:[],
            // 加载
            loading: false,
            // 分页
            currentPage: 1,
            pageSize: 5,
            tocal: 0,
            // 修改/添加
            uORiText:'',
            updateORinsert:'',
            updateform: {
                userId: '',
                roleId:'',
                userName: '',
                realName:'',
                userAddress:'',
                userBank:'',
                userSex:'',
                userTime:'',
                userPhone:'',
                userEmail:'',
                userIdcard:'',
                faceToken:'',
                faceUserid:'',
                faceGroupid:'',
            },
            // 验证
            userRules:{
                userName:[
                    // 必填项验证(必填项、提示信息、失去焦点后触发)
                    { required: true, message: "用户名为必填项", trigger: "blur" },
                    { min: 2, max: 12, message: "长度在3到12个字符", trigger: "blur" }, //长度验证
                ],
                realName:[
                    { required: true, message: "用户名为必填项", trigger: "blur" },
                    { min: 2, max: 12, message: "长度在3到12个字符", trigger: "blur" }, //长度验证
                ],
                userBank:[{ required: true, validator: checkBank, trigger: 'blur'}],
                userPhone:[{ required: true, validator: checkPhone, trigger: 'blur'}],
                userEmail:[{ required: true, validator: checkEmail, trigger: 'blur' }],
                userIdcard: [{ required: true, validator: checkIdNum, trigger: 'blur' }],
            },
            updateFormVisible: false,
            // 角色
            roleSelect:[],
            // 按钮隐藏
            deleteMore: false,
            // 人脸按钮
            uORiFace:'',
            // 人脸识别
            dialogVisible:false,
            userContext:null,
            video: null,
            // 批量删除
            multipleSelection: [],
            multipleSelection1: [],
            // 
            userFace:'',
        }
    },
    created(){
        this.queryUnitList();
    },
    methods:{
        // 查询全部数据 -- 条件分页
        queryUnitList(currentPage){
            this.loading=true;
            if(currentPage!=null){
                if(isNaN(currentPage)){
                    this.currentPage = 1;
                }else{
                    this.currentPage = parseInt(currentPage);
                }
            }else{
                this.currentPage = 1;
            }
            axios.get("http://localhost:8082/user/getUserPage?userName="+this.user.userName+"&realName="+this.user.realName+"&index="+this.currentPage+"&pageSize="+this.pageSize).then(res=>{
                this.tableData = res.data.list
                this.tocal = res.data.tocal
                this.loading=false;
                console.log(res)
            })
        },
        // 重置数据
        redirectUnitList(){
            this.user=this.user1;
            this.queryUnitList(1);
        },
        // 修改/添加
        showEditDialog(row){
            this.updateFormVisible=true;
            // 角色
            axios.get("http://localhost:8082/role/getAllRole").then(res=>{
                this.roleSelect = res.data
            })
            console.log(row.userId)
            if(row.userId!=null){
                this.uORiText = '修改';
                console.log(this.uORiText)
                this.updateform.userId = row.userId;
                this.updateform.userName=row.userName;
                this.updateform.realName = row.realName;
                this.updateform.roleId=row.roleId;
                this.updateform.userAddress=row.userAddress;
                this.updateform.userBank=row.userBank;
                this.updateform.userSex = row.userSex;
                this.updateform.userTime = row.userTime;
                this.updateform.userPhone=row.userPhone;
                this.updateform.userEmail=row.userEmail;
                this.updateform.userIdcard = row.userIdcard;
                this.updateform.faceToken = row.faceToken;
                this.updateform.faceUserid = row.faceUserid;
                this.updateform.faceGroupid = row.faceGroupid;
            }else{
                this.uORiText = '添加';
                console.log(this.uORiText)
                this.updateform = {};
            }
        },
        // 扫描人脸
        scanFace(row){
            this.dialogVisible=true
            this.callCamera();
            console.log(row)
            this.userFace = row.userName
        },
        // 保存修改/添加
        insertUpdateForm(){
            this.updateFormVisible=false;
            if(this.uORiText=="添加"){
                console.log(this.updateform)
                axios.post("http://localhost:8082/user/insertByUser",this.updateform).then(res=>{
                    // 盐和密码固定
                    if(res.data=='ok'){
                        this.queryUnitList(1);
                        this.$message.success("添加成功");
                    }else{
                        this.$message.error("添加失败");
                    }
                })

            }else{
                console.log(this.updateform)
                axios.post("http://localhost:8082/user/updateByUser",this.updateform).then(res=>{
                    console.log(res)
                    if(res.data=='ok'){
                        this.queryUnitList();
                        this.$message.success("编辑成功");
                    }else{
                        this.$message.error("编辑失败");
                    }
                })

            }
        },
        //   关闭添加/修改框
       handleClose() {
           this.updateFormVisible = false;
       },
        // 删除
        deleteUser(id){
            console.log(id)
            axios.get("http://localhost:8082/user/deleteByUserId?id="+id).then(res=>{
                console.log(res)
                if(res.data=='ok'){
                    this.queryUnitList();
                    this.$message.success("删除成功");
                }else{
                    this.$message.error("删除失败");
                }
            })
        },
        // 重置密码
        resetUserPwd(row){
            console.log(row)
            this.$msgbox({
                title:"重置密码",
                dangerouslyUseHTMLString: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showCancelButton: false,
                message:'确定重置密码为 123456 吗?',
            }).then(res1=>{
                console.log("执行："+res1)
                // 执行事件
                axios.post("http://localhost:8082/user/updatePwdByid",row).then(res2=>{
                    console.log(res2.data)
                    if(res2.data!="ok"){
                        this.$message({
                            type: 'info',
                            message: '重置失败'
                        }); 
                    }else {
                        this.$message({
                        type: 'success',
                        message: '重置成功'
                    });
                    }
                }) 
            }).catch(()=>{
                console.log("buzhixing")
            })  
        },
        // 获取勾选内容
        handleSelectionChange(rows) {
            this.deleteMore=true;
            this.multipleSelection1 = rows;
            this.multipleSelection = [];
            this.multipleSelection1.forEach(e=>{
                this.multipleSelection.push(e.userId);
            })
            console.log(this.multipleSelection)
      },
        // 批量删除
        deleteMoreBotton(){
            axios.post("http://localhost:8082/user/deleteByUserIds",this.multipleSelection).then(res=>{
                console.log(res)
                if(res!='ok'){
                    this.queryUnitList(1);
                    this.$message.success("删除成功");
                }else{
                    this.$message.error("删除失败");
                }
            })
        },
        // 添加用户人脸
        ok () {
           this.userContext.drawImage(video, 0, 0, 450, 300);
        var userImgSrc = document.getElementById("canvas").toDataURL("img/png");
        //拿到bash64格式的照片信息
        var faceBase = userImgSrc.split(",")[1];
        axios.get("http://localhost:8082/register?faceBase="+faceBase+"&user="+this.userFace).then(response=>{
            if(response.data!=null){
                this.stopNavigator()
                this.$notify({
                title: '成功',
                message: '人脸录入成功!',
                type: 'success'
                });
            }else{
                this.$notify({
                title: '警告',
                message: '人脸录入失败!',
                type: 'warning'
                });
            }
        })
    },
        cancel () {
            this.dialogVisible = false;
            this.stopNavigator()
        },
        stopNavigator () {
        this.video.srcObject.getTracks()[0].stop()
    },
       callCamera() {
      /**调用摄像头，获取媒体视频流**/
      this.video = document.getElementById("video");
      //返回画布二维画图环境
      this.userContext = canvas.getContext("2d");
      var getUserMedia =
        //浏览器兼容,表示在火狐、Google、IE等浏览器都可正常支持
        navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia;
      //getUserMedia.call(要调用的对象，约束条件，调用成功的函数，调用失败的函数)
      getUserMedia.call(
        navigator,
        { video: true, audio: false },
        function (localMediaStream) {
          //获取摄像头捕捉的视频流
          video.srcObject = localMediaStream;
        },
        function (e) {
          console.log("获取摄像头失败！！");
        }
      );
    },
    },
    
}
</script>
<style lang="less" scoped>

</style>